const {
  request
} = require("../../utils/index.js")
// pages/recruitment/recruitcoopera.js
import WxValidate from '../../utils/WxValidate';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    experience:['不限','在校生','应届生','一年以内','1-3年','3-5年','5-10年','10年以上'],  //工作经验
    school: ['本科', '硕士','博士'], //学历
    expindex: 0, //工作下标
    schindex: 0, //学历下标
    address: "请选择地址", //地址信息
    src: "",
    m_latitude: null, //经度
    m_longitude: null, //纬度
    salaryType: '面谈', //月薪或年薪
    items: [{
        name: 'YMonthly',
        value: '月薪',
      },
      {
        name: 'NMonthly',
        value: '年薪'
      },
      {
        name: 'interview',
        value: '面谈',
        checked: 'true'
      }
    ],

    checkboxArr: [{
        checked: false, //是否选中
        id: "1", //福利id
        name: "餐饮补贴",
      },
      {
        checked: false, //是否选中
        id: "2", //福利id
        name: "住房补贴",
      },
      {
        checked: false, //是否选中
        id: "3", //福利id
        name: "交通补贴",
      },
      {
        checked: false, //是否选中
        id: "4",
        name: "带薪年假",
      },
      {
        checked: false, //是否选中
        id: "5",
        name: "节日福利",
      },
      {
        checked: false, //是否选中
        id: "6",
        name: "健康体检",
      },
      {
        checked: false, //是否选中
        id: "7",
        name: "年终奖",
      },
      {
        checked: false, //是否选中
        id: "8",
        name: "13薪",
      },
      {
        checked: false, //是否选中
        id: "9",
        name: "员工旅游",
      },
      {
        checked: false, //是否选中
        id: "10",
        name: "零食下午茶",
      },
    ], //福利列表
    checkValue: [], //福利
    depValue: [], //福利
    isDep: false, //福利显隐
    d_id: [], //福利id集合

    width: '28vw', //图片宽度
    height: '28vw', //图片高度
    chooesList: [], //视频地址
    chooesID: [], //视频id
    chooesnumber: '', //视频数量
    // shareList: [], //图片的临时路径
    shareID: [], //图片ID
    // sharenumber: '', //已选图片个数
    shareshow: true, //是否可继续添加图片
    chooesshow: true, //是否可继续添加视频
    regadd: '北京市,北京市,东城区', //工作地
    regcity:'北京市',  //工作城市
    
    /* 上传多张图片开始 */
    count: 9, //最多选择图片的张数，默认9张
    uploadUrl: { //图片上传的服务器路径
      type: String,
      value: 'https://tms.sds.com.cn:8300/hw/upload/files'
    },
    showUrl: { //图片的拼接路径
      type: String,
      value: ''
    },
    detailPics: [], //上传的结果图片集合
    detailPicsID: [], //上传的结果图片集合
    /* 上传多张图片结束 */
  },

  regadd: function (e) {
    console.log(e.detail.value)
    this.setData({
      regadd: e.detail.value,
      regcity:e.detail.value[0]
    })
    console.log("携带值为：" + this.data.regadd)
  },

  // 上传视频
  chooseVideo: function (e) {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      camera: 'back',
      maxDuration: 60, //视频最大大小
      success: res => {
        var tempFilePaths = res.tempFilePath;
        wx.uploadFile({
          url: 'https://tms.sds.com.cn:8300/hw/upload/files',
          filePath: tempFilePaths,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
          },
          formData: {
            method: 'POST',
            token: wx.getStorageSync('token'),
            sortVal: 1,
            updFileModule: 'recruit_cooperate',
            updFileType: 'video',
          },
          success(res2) {
            var res = JSON.parse(res2.data)
            if (res.status == 100) {
              that.setData({
                chooesList: res.data.updUrl,
                chooesID: res.data.updId,
                shareshow: false,
                chooesshow: false
              })
            }
          }
        })
      }
    })
  },

  // 视频展示
  chooseshow: function (e) {
    var that = this;
    console.log(12312);
    wx.previewMedia({
      success: this.data.chooesList,
      current: 0,
      type: 'video',
      url: this.data.chooesList[0]
    })
  },

  // 视频删除
  choosedele: function (e) {
    this.setData({
      chooesList: '',
      chooesshow: true,
      shareshow: true
    })
  },
  /* 上传多张图片开始 */
  shareUpload: function (e) {
    var that = this;
    var pics = [];
    that.setData({
      count:9
    })
    that.data.count = that.data.count - that.data.detailPics.length
    wx.chooseImage({
      count: that.data.count, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths; //图片临时地址
        for (var i = 0; i < imgs.length; i++) {
          pics.push(imgs[i])
        }
        that.uploadimg({
          url: that.data.uploadUrl, //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      }
    })
  },
  //多张图片上传
  uploadimg: function (data) {
    wx.showLoading({
      title: '上传中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url.value,
      filePath: data.path[i],
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data',
      },
      formData: {
        method: 'POST',
        token: wx.getStorageSync('token'),
        sortVal: 1,
        updFileModule: 'recruit_cooperate',
        updFileType: 'pic',
      },
      success: (resp) => {
        wx.hideLoading();
        var str = resp.data //返回的结果，可能不同项目结果不一样
        var pic = JSON.parse(str);
        var pic_name = pic.data;
        var detailPics = that.data.detailPics;
        detailPics.push(pic_name)
        this.data.detailPicsID.push(pic.data.updId)
        that.setData({
          detailPics: detailPics,
          shareID:detailPics.updId,
        })
      },
      fail: (err) => {
        console.log(err)
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        if (that.data.detailPics.length == 1) {
          that.setData({
            chooesshow: false
          })
        }
        if (that.data.detailPics.length == 9) {
          that.setData({
            shareshow: false
          })
        }
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用   
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
          var myEventDetail = {
            picsList: that.data.detailPics
          } // detail对象，提供给事件监听函数
          var myEventOption = {} // 触发事件的选项
          that.triggerEvent('myevent', myEventDetail, myEventOption)
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    })
  },
  // 多图上传删除
  sharedele:function(e){
    var newList = [];
    var detailPics = this.data.detailPics;
    for (let i = 0; i < detailPics.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        continue;
      } else {
        newList.push(detailPics[i])
      }
    }
    if (detailPics.length - 1 == 0) {
      this.setData({
        chooesshow: true
      })
      console.log(this.data.chooseshow)
    }
    this.setData({
      count: this.data.count - 1,
      detailPics: newList,
      shareshow: true,
    })
  },
  //多图上传查看
  shareshow: function (e) {
    var that = this;
    var urlList=[];
    var detaurllist = that.data.detailPics
   for(var i=0;i<detaurllist.length;i++){
     urlList.push(detaurllist[i].updUrl);
   }
    wx.previewImage({
      urls: urlList,
      current: urlList[e.currentTarget.dataset.id]
    })
  },
  /* 上传多张图片结束 */

  // 选择月薪或是年薪
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      salaryType:e.detail.value
    })
  },
  //工作经验选择
  chanexperience: function (e) {
    this.setData({
      expindex: e.detail.value
    })
    console.log(this.data.experience[this.data.expindex])
  },

  //学历选择
  chanSchool: function (e) {
    this.setData({
      schindex: e.detail.value
    })
    console.log(this.data.school[this.data.shcindex])
  },

  //控制福利的显隐
  isDep: function () {
    this.setData({
      isDep: true,
    })
  },
  //取消按钮
  cancel: function () {
    this.setData({
      isDep: false,
      isPer: false
    })
  },
  checkbox: function (e) {
    var index = e.currentTarget.dataset.index; //获取当前点击的下标
    var checkboxArr = this.data.checkboxArr; //选项集合
    checkboxArr[index].checked = !checkboxArr[index].checked; //改变当前选中的checked值

    this.setData({
      checkboxArr: checkboxArr
    });
  },
  checkboxChange: function (e) {
    var checkValue = e.detail.value;
    this.setData({
      checkValue: checkValue
    });
  },
  confirm: function () { // 确定
    this.setData({
      isDep: false,
    })
  },

  //打开腾讯地图自主选择地址
  onChangeAddress: function (e) {
    wx.navigateTo({
      url: "/pages/position/position"
    });
  },

  // 非空验证
  initValidate() {
    const rules = {
      postName: {
        required: true,
      },
      salary: {
        required: true,
      },
      companyName: {
        required: true,
      },
      postInfo: {
        required: true,
      },
      companyInfo: {
        required: true,
      }
    }
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      postName: {
        required: '请输入职位名称',
      },
      salary: {
        required: '请输入月薪或年薪',
      },
      companyName: {
        required: '请输入招聘公司名称',
      },
      postInfo: {
        required: '请输入职位信息'
      },
      companyInfo: {
        required: '请输入公司信息'
      }
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },


  async submitForm(e) {
    /***4-3(表单提交校验)*/
    const params = e.detail.value
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    //验证通过以后==>
    //上传文件
    if (this.data.chooesID == '') { //视频为空
      this.setData({
        file: this.data.detailPicsID
      })
    } else {
      let arrayfile = [];
      arrayfile.push(this.data.chooesID.toString());
      this.setData({
        file: arrayfile
      })
    }
    console.log(this.data.shareList)
    //地址非空
    if (this.data.address == "请选择地址") {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
    }else if(this.data.file==''){
      wx.showToast({
        title: '请上传图片或视频',
        icon: 'none'
      })
    } else {  
      let salary=e.detail.value.salary
      if(e.detail.value.salary=='0'){
        salary='面谈'
      }
      let par = {
        url: 'hw/portal/recruited/save?token=' + wx.getStorageSync('token'),
        data: {
          postName: e.detail.value.postName,  //职位名称
          workExperience: this.data.experience[this.data.expindex],  //工作经验
          workAddress: this.data.regadd.toString(),  //工作地
          workCity:this.data.regcity,   //工作城市
          education: this.data.school[this.data.schindex],  //学历
          salary: salary,  //薪资
          salaryType:this.data.salaryType, //薪资类型
          companyName: e.detail.value.companyName,  //招聘公司
          postLabel: this.data.checkValue.toString()==""?"无":this.data.checkValue.toString(),  //  福利
          workGps: this.data.address,  //  工作地
          postInfo: e.detail.value.postInfo,  //  岗位信息
          companyInfo: e.detail.value.companyInfo,  //  公司信息
          files: this.data.file  //文件
        }, 
        method: 'POST',
        header: {
          'content-type': 'application/json', // 默认值
          // 'token':wx.getStorageSync('token')
        },
      }
      var result = await request(par);
      if (result.status == 100) {
        wx.showModal({    
          title: '发布成功！',
          confirmText: "确认",
          showCancel: false,
          success:function(res){
            if(res.confirm){
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: '发布失败！请稍后重试！',
          icon: 'none'
        })
      }
    }
  },

  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initValidate();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.navigateBack({
      delta: 2
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})